package dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import dao.RateDao;
import dao.RowMapper;
import entity.Food;
import entity.FoodSize;
import entity.FoodType;
import entity.Rate;

public class RateDaoImpl implements RateDao{
	JDBCTemplate jdbc =new JDBCTemplate();
	
	private class rowMapperImpl implements RowMapper<Rate>{
		@Override
		public Rate rowMapper(ResultSet rs) throws SQLException {
			FoodType foodtype = new FoodType();
			foodtype.setFtId(rs.getInt("foodTypeId"));
			foodtype.setFoodTypeName(rs.getString("foodTypeName"));
			
			
			Food food = new Food();
			food.setfId(rs.getInt("foodid"));
			food.setFoodType(foodtype);
			food.setFoodName(rs.getString("foodname"));
			food.setFoodprice(rs.getDouble("Foodprice"));
			food.setImageFile(rs.getString("imageFile"));
			food.setDescription(rs.getString("description"));
			
			FoodSize foodsize = new FoodSize();
			foodsize.setFsId(rs.getInt("foodsizeid"));
			foodsize.setFoodSizeName(rs.getString("foodSizeName"));
			
			Rate rate =new Rate();
			rate.setRateId(rs.getInt("RateId"));
			rate.setRatio(rs.getDouble("ratio"));
			rate.setFood(food);
			rate.setFoodSize(foodsize);
			return rate;
			
		}
	}
	
	@Override
	public List<Rate> queryAllRate() {
		return query(null, null);
	}

	@Override
	public Rate queryRateByRateId(int rateId) {
		return query("rateId", rateId).get(0);
	}

	@Override
	public List<Rate> queryRateByFoodTypeId(int foodTypeId) {
		return query("foodTypeId", foodTypeId);
	}
	private List<Rate> query(String type,Integer id){
		List<Rate> list = new ArrayList<Rate>();
		String sql = "SELECT rate.*,food.`foodTypeId`,food.`foodName`,"
				+ "food.`foodprice`,food.`imageFile`,food.`description`,"
				+ "foodtype.`foodTypeName`,foodsize.`foodSizeName`"
				+ "FROM rate "
				+ "INNER JOIN food ON rate.`foodId`=food.`fId`"
				+ "INNER JOIN foodtype ON food.`foodTypeId`=foodtype.`ftId`"
				+ "INNER JOIN foodsize ON foodsize.`fsId`=rate.`foodSizeId`";
		if(id!=null){
			if ("rateId".equals(type)) {
				sql+=" where rateId=? ";
			}else if("foodTypeId".equals(type)){
				sql+=" where foodTypeId=? ";
			}
			list=jdbc.queryAll(sql, new rowMapperImpl(), id);
		}else{
			list=jdbc.queryAll(sql, new rowMapperImpl());
		}
		return list!=null&&list.size()>0?list:null;
	}
	public static void main(String[] args) {
		RateDao rd = new RateDaoImpl();
		List<Rate> list=rd.queryRateByFoodTypeId(2);
		System.out.println(list.size());
	}

	@Override
	public void addRate(Rate rate) {
		String sql ="INSERT  INTO `rate`(`foodId`,`foodSizeId`,`ratio`) VALUES(?,?,?)";
		jdbc.CUDObject(sql, rate.getFood().getfId(),rate.getFoodSize().getFsId(),rate.getRatio());
		
	}

}
